//
//  LZSearchCollectionView.m
//  laziz_Consumer
//
//  Created by XMac on 16/10/25.
//  Copyright © 2016年 XBN. All rights reserved.
//

#import "LZSearchCollectionView.h"
#import "LZMostSearchCollectionViewCell.h"
#import "LZSearchHistoryCollectionViewCell.h"
#import "LZSearchCollectionReusableView.h"
#import "LZSearchFooterCollectionReusableView.h"
#import "LZSearchHistoryUserdefault.h"

extern NSString *bound;

@interface LZSearchCollectionView () <UICollectionViewDataSource, UICollectionViewDelegateFlowLayout>
@property(nonatomic , strong) NSArray *mostDats;
@property(nonatomic , strong) NSArray *historyDatas;
@end


@implementation LZSearchCollectionView


- (instancetype)initWithFrame:(CGRect)frame collectionViewLayout:(UICollectionViewLayout *)layout {
    self = [super initWithFrame:frame collectionViewLayout:layout];
    if (self) {
        
        _mostDats = @[];
        
        self.backgroundColor = [UIColor clearColor];

        self.alwaysBounceVertical = YES;
        
        self.dataSource = self;

        self.delegate = self;

        [self registerCell];
    }
    return self;
}

-(void)refreshUserdefaultData{
    NSMutableArray *searchHistory = [LZSearchHistoryUserdefault sharedInstance].searchHistoryResults.mutableCopy;
    
    if (searchHistory.count > 20) {
        NSRange range = NSMakeRange(0, searchHistory.count - 10);
        [searchHistory removeObjectsInRange:range];
        
        [LZSearchHistoryUserdefault sharedInstance].searchHistoryResults = searchHistory;
    }
    
    [searchHistory sortUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        return NSOrderedDescending;
    }];
    
    if (searchHistory.count > 10) {
        [searchHistory removeObjectsInRange:NSMakeRange(10, searchHistory.count - 10)];
    }
    
    _historyDatas = searchHistory.copy;
    
    [self reloadData];
}


-(void)refreshData:(NSArray *)tags{
    if (tags && _mostDats != tags) {
        _mostDats = tags;
        [self reloadData];
    }
}


#pragma
#pragma mark private method

- (void)registerCell {

    [self registerNib:[UINib nibWithNibName:@"LZMostSearchCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"LZMostSearchCollectionViewCell"];

    [self registerNib:[UINib nibWithNibName:@"LZSearchHistoryCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:@"LZSearchHistoryCollectionViewCell"];


    [self registerNib:[UINib nibWithNibName:@"LZSearchCollectionReusableView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"LZSearchCollectionReusableView"];

    [self registerNib:[UINib nibWithNibName:@"LZSearchFooterCollectionReusableView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"LZSearchFooterCollectionReusableView"];
    
    [self registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"grayfooter"];
    
    
}


#pragma
#pragma mark UICollectionViewDelegateFlowLayout

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 2;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (section == 0) {
        return _mostDats.count;
    } else {
        return _historyDatas.count;
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {

    switch (indexPath.section) {
        case 0:
            return [LZMostSearchCollectionViewCell getCellSizeWithText:_mostDats.count>0 ?_mostDats[indexPath.row] : @"label1"];
        case 1:
            return CGSizeMake(CGRectGetWidth(collectionView.frame), 55);
    }

    return CGSizeZero;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    switch (section) {
        case 0:
            return UIEdgeInsetsMake(20, 10, 20, 20);
        case 1:
            return UIEdgeInsetsZero;
    }

    return UIEdgeInsetsZero;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    if (section == 1) {
        return 0;
    }
    return 20;
}


- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 20;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section {

    return CGSizeMake(CGRectGetWidth(collectionView.frame), 50);
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section {

    if (section == 0) {
        return CGSizeMake(CGRectGetWidth(collectionView.frame), 10);
    }
    else if (section == 1) {
        return CGSizeMake(CGRectGetWidth(collectionView.frame), 50+20);
    }

    return CGSizeZero;
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath {
    if (kind == UICollectionElementKindSectionHeader) {

        LZSearchCollectionReusableView *header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"LZSearchCollectionReusableView" forIndexPath:indexPath];

        switch (indexPath.section) {
            case 0:
                [header changeTitle:LZLocalizedString(@"search_hot", nil)];
                break;
            case 1:
                [header changeTitle:LZLocalizedString(@"search_history", nil)];
                break;
        }

        return header;
    } else if (kind == UICollectionElementKindSectionFooter) {
        if (indexPath.section == 0) {
            UICollectionReusableView *grayFooter = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"grayfooter" forIndexPath:indexPath];
            grayFooter.backgroundColor = UIColorFromRGB(0xeeeeee, 1);
            return grayFooter;

        }
        else if (indexPath.section == 1) {
            LZSearchFooterCollectionReusableView *footer = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionFooter withReuseIdentifier:@"LZSearchFooterCollectionReusableView" forIndexPath:indexPath];
            
            [footer setClearBlock:^{
                [LZSearchHistoryUserdefault sharedInstance].searchHistoryResults = @[].mutableCopy;
                
                [self refreshUserdefaultData];
            }];
            
            return footer;
        }
        
    }
    return nil;
}


- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

    switch (indexPath.section) {
        case 0: {
            LZMostSearchCollectionViewCell *mostCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"LZMostSearchCollectionViewCell" forIndexPath:indexPath];
            
            if (_mostDats) {
                NSString *content = _mostDats[indexPath.row];
                
                [mostCell changeTitle:content];
            }
            
            return mostCell;
        }
        case 1: {
            LZSearchHistoryCollectionViewCell *historyCell = [collectionView dequeueReusableCellWithReuseIdentifier:@"LZSearchHistoryCollectionViewCell" forIndexPath:indexPath];
            
            if (_historyDatas) {
                NSString *content = _historyDatas[indexPath.row];
                [historyCell changeTitle:[content componentsSeparatedByString:bound][0]];
            }
            

            return historyCell;
        }
    }

    return nil;
}


-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    switch (indexPath.section) {
        case 0:
        {
            if (_mostSearchSelectBlock) {
                _mostSearchSelectBlock(_mostDats[indexPath.row]);
            }
        }
            break;
        case 1:
        {
            NSString *content = _historyDatas[indexPath.row];
            NSArray *resultArray = [content componentsSeparatedByString:bound];
            NSString *resultMessage = @"";
            NSString *resultType = @"";
            NSString *resultId = @"";
            if (resultArray.count>0) {
                resultMessage = resultArray[0];
            }
            if (resultArray.count>1) {
                resultType = resultArray[1];
            }
            if (resultArray.count>2) {
                resultId = resultArray[2];
            }
            //跳转
            if (_historySelectBlock) {
                _historySelectBlock(resultMessage,resultType,resultId);
            }
        }
            break;
    }
}

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
}


@end
